<template>
  <!-- 选择成员-->
  <a-modal :width="500" v-model:visible="showUsers" title="选择成员" title-align="start" ok-text="确认添加" :mask-closable="false" @cancel="closedDialog" @ok="submitData">
    <a-space style="margin-bottom: 10px">
      <a-input v-model="searchKey" style="width: 300px" placeholder="" allow-clear />
      <a-button type="primary" @click="searchDataByVal">搜索</a-button>
    </a-space>

    <div class="tree-w">
      <a-tree
        :checkable="true"
        ref="treeRef"
        :default-expand-all="true"
        v-model:checked-keys="checkedList"
        :fieldNames="{
          key: 'key',
          title: 'userName',
          children: 'children',
        }"
        :data="userList"
        checkedStrategy="child"
      />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, computed, nextTick } from 'vue'
  import { getOrganizesWithUser } from '@/api/system'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
  })

  const showUsers = ref(props.isShow)
  const searchKey = ref()
  const originTreeData = ref<any>([]) //角色列表
  const userList = ref<any>([]) //角色列表
  const checkedList = ref<any>([]) //
  const treeRef = ref()

  // 获取用户列表
  async function getUserList() {
    const res: any = await getOrganizesWithUser()
    originTreeData.value = res?.data || []
    setUserList(originTreeData.value)
    userList.value = searchData()
    nextTick(() => {
      treeRef.value.expandAll(true)
    })
  }
  getUserList()

  function setUserList(list: Array<any>) {
    list.forEach((item: any) => {
      item.key = item.deptName + 'id:' + item.id
      item.userName = item.deptName
      if (!item.children?.length && !item.userList?.length) {
        item.disabled = true
      }
      if (item.children?.length) {
        setUserList(item.children)
      }
      if (item.userList?.length) {
        let userList = item.userList.map((user: any) => {
          return {
            id: user.id,
            userName: user.userName,
            key: user.userName + 'id:' + user.id,
          }
        })
        item.children = [...(item.children || []), ...userList]
      }
    })
  }
  function searchDataByVal() {
    userList.value = searchData()
  }
  function searchData() {
    if (!searchKey.value) return originTreeData.value
    const loop = (data: Array<any>) => {
      const result: Array<any> = []
      data.forEach((item: any) => {
        if (item.userName?.toLowerCase().indexOf(searchKey.value.toLowerCase()) > -1) {
          result.push({ ...item })
        } else if (item.children) {
          const filterData = loop(item.children)
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            })
          }
        }
      })
      return result
    }

    return loop(originTreeData.value)
  }

  // 确认
  async function submitData() {
    let list: Array<any> = []
    checkedList.value.forEach((val: string) => {
      let vals = val?.split('id:')
      if (vals) {
        list.push({
          userId: vals[1],
          userName: vals[0],
        })
      }
    })
    console.log(list)
    emit('success', list)
    closedDialog()
  }
  // 关闭
  function closedDialog() {
    showUsers.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .tree-w {
    height: calc(84vh - 240px);
    overflow-y: auto;
  }
</style>
